App.controller("orderListCtrl",function($scope, $rootScope, $location, $http, $compile, path, $sce,$timeout, publicService) {
	
	$scope.search = {};		//搜索条件
	$scope.product = {};   //订单详细信息
	$scope.account = {};   //设置说明
	var gifNum =1;         //产品信息记录    有几条
	
	$scope.orderExplain_show = true;		//订单说明（显示）
	
	$scope.shopName_hidden = false;		//所属专卖店、报名专卖店（显示）
	$scope.company_hidden = false;		//分公司（显示）
	
	$scope.company_shop_table_show = true;		//分公司,专卖店（table显示）
	$scope.shop_table_show = false;				//专卖店（table显示）
	
	var countNumsData = null;  //抽奖次数规则 
	var fullPresent = null;  //满赠规则
	var alertModel = {};	//alert模态框
	
	var stateObj = [
	             	{
		            	id: "",
		 				text: "请选择"
		             },
		             {
		            	 id: "1",
		            	 text: "物流"
		             },
		             {
		            	 id: "2",
		            	 text: "安装"
		             },
		             {
		            	id: "3",
		            	text: "售后"
		             },
		             {
		            	id: "4",
		            	text: "关闭"
		             }  
	        ];
	
	
	if(userInfo.user_level == 3){
		$scope.showThree = true;
		$scope.hideOtherOrder = true;    //隐藏另一个订单
		
		$scope.orderExplain_show = false;
	}else if(userInfo.user_level ==2){
		$scope.showTwo = true;   //分公司的时候显示
		$scope.showTwoOrOne = true;  //空白的那个 （样式对其）
		$scope.hideOtherOrder = true;    //隐藏另一个订单
		
		$scope.company_hidden = true;
		
		$scope.company_shop_table_show = false;
		$scope.shop_table_show = true;
	}else if(userInfo.user_level ==1){
		$scope.showTwoOrOne = true;  //空白的那个 （样式对其）
		$scope.showOne = true;
		
		$scope.orderExplain_show = false;
		
		$scope.shopName_hidden = true;
		$scope.company_hidden = true;
		
		$scope.company_shop_table_show = false;
	}else if(userInfo.user_level ==0){
		$scope.hideOtherOrder = true;
		$scope.showOne = false;
		
		$scope.orderExplain_show = false;
	}
	$scope.orderStates = function(){
		$("#orderState").kendoDropDownList({
			dataTextField: "text",
		    dataValueField: "id",
			dataSource:stateObj
		});
	};
	//付款方式
 /*	$("#paymentMethod").kendoDropDownList({
	    dataTextField: "name",
	    dataValueField: "name",
		dataSource: [
					{
						id:"",
						name:"请选择"
					},
					{
						
						id:"",
						name:"现金"
					},
		            {
						id:"",
						name:"pos机"
	            	},
	            	{
	            		id:"",
	            		name:"微信"
	            	},
	            	{
	            		id:"",
	            		name:"支付宝"
	            	},
	            	{
	            		id:"",
	            		name:"刷卡"
	            	}
	      ]
 	});*/
	$scope.orderTypes = function(){
		$("#order_types").kendoDropDownList({
			dataTextField: "text",
		    dataValueField: "id",
			dataSource: [
			             {
			            	id: "",
			 				text: "请选择"
			             },
			             {
			            	 id: "1",
			            	 text: "活动订单"
			             },
			             {
			            	 id: "2", 
			            	 text: "普通订单"
			             }
	        ]
		});
	};
	//编辑状态
	$scope.editState = function(id,stateId){
		var postData = {
				orderId: id,
				orderState: stateId
		};
		
		$http({
			   url: path+"/server/updateOrderStatus",
			   method: 'POST',
			   data: angular.toJson(postData)
		}).success(function(data){
			if(data.code==0){  //成功
				$scope.grid.dataSource.page(1);
			}else if(data.code==1){  //失败
				
			}
		}).error(function(data){
			console.log(data);   
		})
	}	
	
	//产品订单
	$scope.gridOptions = {
			dataSource : {
				transport : {
					read : {
						url : path+"/server/selectOrderPage",
						type : 'POST',
						dataType : "json",
						contentType : "application/json"
					},
					parameterMap : function(options, operation) {
						if (operation == "read") {
							var sort = [{dir:"desc",field:"create_time"}];
							if(options.sort!=null && options.sort.length>0 ){
								if(options.sort[0].field=="createTime"){
									options.sort[0].field="create_time";
								}else{
									options.sort[0].field="create_time";
								}
								
								sort=options.sort;
							}
							
							var parameter = {
								page : options.page, //当前页
								pageSize : options.pageSize,
								param:{
									activityCode:$scope.search.order_code,//活动编号
									activityName:$scope.search.activity_names,//活动名称
									orderState:$('#orderState').val(),//订单状态
									filiale:$scope.search.filiale,//分公司
									shopName:$scope.search.shop_name,//专卖店名称
									sellerName:$scope.search.order_guide,//专属顾问
									productModel:$scope.search.product_type,   //产品型号
									customerPhone:$scope.search.phone,  //联系电话
									createTime:$('#order_down_time').val(),  //下单时间
									
									province:$('#province').val(),//省
									city:$('#city').val(), // 市
									district:$('#area').val(),//区
									sort:sort
								}
							};
							console.log('查询参数',parameter);
							return kendo.stringify(parameter);
						}
					},
				},
				pageSize : 10,
				serverPaging : true,
				serverSorting: true,
				schema : {
					data : function(d) {
						$scope.exData=d.result.data;
						return d.result.data;
					},
					total : function(d) {
						return d.result.total; //总条数
					},
					model: {
				          id: "id",
				          fields: {
				        	  productModel: { editable: false},
				        	  customerName: { editable: false},
				        	  customerPhone: { editable: false},
				        	  shopName: { editable: false},
				        	  filiale: { editable: false},
				        	  sellerName: { editable: false},
				        	  realPayPrice: { editable: false},
				        	  activityCode: { editable: false},
				        	  activityName: { editable: false},  
				        	  createTime: { editable: false},
				        	  orderId: { editable: false},
				        	  createTime: { editable: false}
				          }
				    }
				},
			},
			pageable : {  //分页
				pageSizes: [10, 20, 50, 100],  //每页显示记录数
			  },   
			sortable: {   //排序
				//allowUnsort: false,  //允许无序
			    mode: "single"     //排序模式：single，multiple
			  },
			/*editable: {   //编辑
			    mode: "inline"   //整行编辑
			  },*/
			editable: true,  //true：单个编辑；popup：弹出新页面编辑
	        dataBound: function(e) {	//数据绑定成功
	        	var rows = this.items();
		        var page = this.pager.page() - 1;
		        var pagesize = this.pager.pageSize();
		        $(rows).each(function () {
		            var index = $(this).index() + 1 + page * pagesize;
		            var rowLabel = $(this).find(".row-number");
		            $(rowLabel).html(index);
		        });
	        	
		    	console.log("【Grid 数据绑定成功】");
		    },
			columns : [
					{    
						title : "序号",
						field : "orderId", 
						width : "50px",
						template:"<input type='checkbox' class='recordClass' id='#: orderId #' value='#: orderId #' />"+"<span class='row-number subTitle '></span>"
					},
					{
						field : "activityCode",         
						title : "活动编号",     
						width : "150px"
					},
					{
						field : "createTime",         
						title : "下单日期",     
						width : "80px"
					},
					{
						field : "activityName",         
						title : "活动名称",     
						width : "80px"
					},

					{
						field : "orderState",         
						title : "订单状态",     
						width : "80px",
						template: function(e){
					    	if(userInfo.user_level==2){
					    		return '<div class="canEdit">'+e.orderState+'</div>';
					    	}else{
					    		return e.orderState;
					    	}
					    },
					    editor: function (container, options) {
					    	if(userInfo.user_level==2){
					    		$('<input data-bind="value:' + options.field + '"/>')
						        .appendTo(container)
						        .kendoDropDownList({
						           dataTextField: "text",
								   dataValueField: "id",  //id
						           dataSource: stateObj,
						 	       change: function(e) {
						 	         var value = this.value();;
						 	         $scope.editState(options.model.orderId,value);
						 	       }
						        });
					    	}else{
					    		if(options.model.orderState){
					    			$('<span>'+options.model.orderState+'</span>')
							        .appendTo(container);
					    		}
					    	}	
						},						
					},
					{
						field : "productModel",         
						title : "产品型号",     
						width : "60px",

					},
					{
						field : "customerName",         
						title : "买家",     
						width : "160px"
					},
					{
						field : "customerPhone",         
						title : "联系电话",     
						width : "80px"    
					},
					{
						field : "shopName",         
						title : "所属专卖店",     
						width : "80px",
						hidden: $scope.shopName_hidden
					},
					{
						field : "signShopName",         
						title : "报名专卖店",     
						width : "80px",
						hidden: $scope.shopName_hidden
					},
					{
						field : "filiale",         
						title : "分公司",     
						width : "80px" ,
						hidden: $scope.company_hidden
					},
					{
						field : "sellerName", 
						title : "专属顾问", 
						width : "80px"    
					},
					{
						field : "realPayPrice",         
						title : "实收金额",     
						width : "80px"    
					},
					{
						field : "",         
						title : "操作",     
						width : "100px",
						template: function(e){
							if(e.order_state == 4){
								var	template_html  ='<div class="operation k-state-default " ng-click="showDetails(\''+e.orderId+'\',0)">查看详情</div>'
									+'<div class="operation k-state-default " ng-click="lookCloseCause(\''+e.orderId+'\',\''+e.closeWay+'\',\''+e.closeCause+'\')">查看关闭原因</div>';
								return template_html;
							}else{
								var	template_html  = '<div class="operation k-state-default " ng-click="showDetails(\''+e.orderId+'\',0)">查看详情</div>';
								return template_html;
							}
						}
						
					}
			]
		};


	//查询
	$scope.search=function(){
		$scope.grid.dataSource.page(1);
		$scope.getorderNum();   //
	}
	
//请求列表的总总额 以及订单数量
	$scope.getorderNum = function(){
		// 搜索传的的对象
		var productObject = {
				activityCode:$scope.search.order_code,//活动编号
				activityName:$scope.search.activity_names,//活动名称
				orderState:$('#orderState').val(),//订单状态
				filiale:$scope.search.filiale,//分公司
				shopName:$scope.search.shop_name,//专卖店名称
				sellerName:$scope.search.order_guide,//专属顾问
				productModel:$scope.search.product_type,   //产品型号
				customerPhone:$scope.search.phone,  //联系电话
				createTime:$('#order_down_time').val(),  //下单时间
				
				province:$('#province').val(),//省
				city:$('#city').val(), // 市
				district:$('#area').val()//区
			};
		$http({
			   url: path+"/server/selectOrderTotalMoney",
			   method: 'POST',
			   data:angular.toJson(productObject)
				   
		}).success(function(data){
			if(data.code=='0'){
				$scope.order_totalprice = data.result.totalMoney;  //总金额
				$scope.order_count = data.result.sum;    //订单数量
			}else{
				alert('接口出错！请联系管理员');
			}
		}).error(function(data){
			console.log(data);   
		});
	}
	
	//显示详情(0 表示详情，1表示用编辑(暂无))
	$scope.showDetails = function(id,num){
		$http({
			   url: path+"/server/selectOrderDetail",
			   method: 'POST',
			   data:id
		}).success(function(data){
			
			if(data.code==0){  //成功
				var datails = data.result;
				$scope.booking_detail.center().open();   //打开弹框  
				$('#box_product .newProduct').remove();   //清空产品信息
				console.log("显示详情页  ",datails);
				if(datails){   //有详情信息
					$scope.product.orderId = datails.orderId; //订单id
					$scope.product.orderCode = datails.orderCode;   //订单编号
					$scope.product.activityName = datails.activityName;   //活动名称
					$scope.product.activityCode = datails.activityCode;   //活动编号
					$scope.product.createTime = datails.createTime;   //下单时间
					$scope.product.orderState = stateObj[datails.orderState].text;   //订单状态	
					$scope.product.sellerName = datails.sellerName;   //专属顾问
					$scope.product.sellerPhone = datails.sellerPhone;   //专属顾问电话
					$scope.product.customerName = datails.customerName;   //客户姓名
					$scope.product.customerPhone = datails.customerPhone;   //联系电话
					
					$scope.product.filiale = datails.filiale; 
					$scope.product.shopName = datails.shopName; 
					$scope.product.signShopName = datails.signShopName; 
					
					//【收货信息】
					$scope.product.consignee = datails.consignee;   //收货人
					$scope.product.consigneePhone = datails.consigneePhone;   //联系电话
					$scope.product.consigneeAddress = datails.consigneeAddress;   //收货地址
					
					for(var i=1;i<datails.productInfoList.length;i++){
						$scope.addgif();
					}
					
					//【产品信息】
					$timeout(function(){
						var detailNum = 1;
						$.each(datails.productInfoList,function(index,objs){
							var box_products = $('#box_product .product_infos_show:eq('+parseInt(detailNum-1)+')');
							$(box_products).children("input:nth(0)").val(objs.productModel);  //产品型号
							$(box_products).children("input:nth(1)").val(objs.price);  //产品单价
							$(box_products).children("input:nth(2)").val(objs.num);  //购买数量
							$(box_products).children("input:nth(3)").val(objs.totalPrice);  //产品总价
							detailNum++;
						});
				    }, 100);

					//【支付信息】
					if(datails.depositPrice){
						$scope.product.depositPrice = datails.depositPrice;//定金
					}else{
						$scope.product.depositPrice =0;//定金
					}
					
					$scope.product.realPayPrice = datails.realPayPrice;//实收金额
					$scope.product.isUseActivityCard = datails.isUseActivityCard;//是否使用卡券
					$scope.paymentMethod = datails.payStatus;//支付方式
//					$("#paymentMethod").data("kendoDropDownList").value(datails.payStatus);//支付方式
					console.log(datails.activityDetail);
					var activity_name_num = 1;
					$.each(datails.activityDetail,function(index,objs){
						if(activity_name_num== 1){
							$scope.activity_name1 = objs.name+'次数';//抽奖的名字
							$scope.activity_num1 = objs.num;//抽奖次数
							activity_name_num++;
							$('#activity1').val(objs.itemId);  
						}else{
							$scope.activity_name2 = objs.name+'次数';//砸金蛋名字
							$scope.activity_num2 = objs.num;//砸金蛋次数
							$('#activity2').val(objs.itemId);  
						}

					});
					
					$scope.product.prizes = datails.prizes;//奖品
					$scope.product.prize = datails.prize;//满赠礼品				
					
					//【备注、说明】
					$scope.product.explain = datails.explain;   //说明
					$scope.product.remarks = datails.remarks;   //备注
					countNumsData =datails.activityNumRule; //抽奖次数的计算
					fullPresent = datails.activityPresentRule;  //满赠规则
					
					if(num == 0){  //查看详情
						$("table input").attr("disabled","true");//让所有的input变为只读
						$('#box_product .add_reduce').hide();
						$('#productSubmitButton').hide();
//						$("#paymentMethod").data("kendoDropDownList").readonly(true);
						$("textarea").attr("disabled","true");
					}else if(num == 1){
						$("table input").removeAttr("disabled");//让所有的input变为只读
//						$('#box_product .add_reduce').show();
						$('#productSubmitButton').show();
//						$("#paymentMethod").data("kendoDropDownList").readonly(false);
//						$("textarea").attr("disabled","false");
						$("textarea").removeAttr("disabled");
					}
				}else{
					alert("暂无详情信息！");
				}
				
				
			}else if(data.code==1){  //失败
				alert(data.message);
			}
		}).error(function(data){
			alert(data);   
		})
	}
//新增产品
	$scope.addgif = function(){
		if(gifNum<=50){
			gifNum = ++gifNum;    //每次点击增加一个
			var html1 =	'<div class="product_infos_show productId'+gifNum+' newProduct">'
							+'<img class="add_reduce" src="../../images/icon/reduce.png" ng-click="removergif('+gifNum+')">'
							+'<p class="boxInfo1">产品型号：</p>'
							+'<input class="k-textbox boxInfo2" />'
							+'<p class="boxInfo1">产品单价：</p>'
							+'<input  class="k-textbox boxInfo2" ng-blur="productCount()"/>'
							+'<p class="boxInfo1">购买数量：</p>'
							+'<input  class="k-textbox boxInfo2"  ng-blur="productCount()"/>'
							+'<p class="boxInfo1">产品总价：</p>'
							+'<input class="k-textbox boxInfo2" />'
						+'</div>';
			html1 = $compile(html1)($scope);  
			$(html1).appendTo($('#box_product'));
		}else{
			alert("最多可以增加50个礼品！");
		}
	};

//删除增加的礼品
	$scope.removergif = function(id){
		$('#box_product .productId'+id+'').remove();
		gifNum = --gifNum;    //每次点击增加一个
		
	};
//计算产品的总价
	$scope.productCount = function(index){
		var tag =angular.element(event.target).parent().children('.boxInfo2');
		if(tag[1].value&&tag[2].value){
			tag[3].value = tag[1].value * tag[2].value;
			console.log(tag[3].value);
		}

	}
//计算砸金蛋次数、抽奖次数
	$scope.calculateMoney = function(){
		var depositPrice = parseInt($scope.product.depositPrice);  //预付定金
		var giftNum = [];   //满奖的礼物
		if(countNumsData){
			var activity_name_num = 1;
			$.each(countNumsData,function(index,objs){
				if(activity_name_num == 1){
					var motion = depositPrice/(objs.useMoney);  //第一个的
					$scope.activity_name1 = objs.name+'次数';//抽奖的名字
					$scope.activity_num1 = motion;//抽奖次数
					activity_name_num++;
				}else{
					var motion = depositPrice/(objs.useMoney);  //第二个的	
					$scope.activity_name2 = objs.name+'次数';//砸金蛋名字
					$scope.activity_num2 = motion;//砸金蛋次数
				}
			});
		}
		$.each(fullPresent,function(index,objs){
			
			if(depositPrice - objs.useMoney >=0){
				giftNum.push(objs.gift);
			}
			
		});
		$scope.product.prize = giftNum.join("-");   //满减礼物的展示
	};
//设置说明
	$scope.accountSet = function(){
		
		$http({
			   url: path+"/server/selectExplain",
			   method: 'POST'
		}).success(function(data){
			if(data.code=='0'){
				if(data.result){
					$scope.account.activityExplain = data.result.activityExplain; //设置说明
				}
			}
			$scope.accountSet1.center().open();   //打开弹框
		}).error(function(data){
			console.log(data);   
		});
	};
//提交设置说明
	$scope.SubmitAcount = function(){
		$http({
			   url: path+"/server/addOrderExplain",
			   method: 'POST',
			   data:angular.toJson($scope.account)
		}).success(function(data){
			if(data.code == "0"){
				alert("操作成功！");
				$scope.accountSet1.center().close();   //打开弹框  
			}
		}).error(function(data){
			console.log(data);   
		});
	};
	//查看关闭原因
	$scope.lookCloseCause = function(id,state,cause){
		if(state==1){
			$scope.close_explain =cause;  //打开弹窗 
			$scope.booking_close.center().open();   //打开弹框  
		}else if(state==2){
			$scope.close_explain = "后台关闭";  //打开弹窗 
			$scope.booking_close.center().open();   //打开弹框  
		}

	}
	//提交关闭订单的原因	
	$scope.SubmitCloses = function(){
		$scope.booking_close.center().close();   //关闭弹窗
	}
	//提交
	$scope.productSubmit = function(){
		if(!$scope.product.consignee){
			alert('请填写收货人名称！');
			return;
		}
		if(!$scope.product.consigneePhone){
			alert('请填写联系电话！');
			return;
		}
		if(!$scope.product.consigneeAddress){
			alert('请填写收货地址！');
			return;
		}
		var box_products = $('#box_product .product_infos_show');
		$scope.product.productInfoList = [];  //产品信息
		$scope.product.num = [];   //活动属性
		var orderPrice = null;
		//产品信息
		$.each(box_products,function(index,objs){
			console.log(objs);
			var object = {};
			object.productModel = $(objs).children("input:nth(0)").val();   //产品型号
			object.price = $(objs).children("input:nth(1)").val();   //产品单价
			object.num = $(objs).children("input:nth(2)").val();  //购买数量
			object.totalPrice = $(objs).children("input:nth(3)").val();  //产品总价
			$scope.product.productInfoList.push(object);   //所有产品的信息
			orderPrice+=parseInt(object.totalPrice);//订单单价
		});
		$scope.product.orderPrice = orderPrice;  //订单总额
		$scope.product.payStatus = $scope.paymentMethod;  //付款方式
		
		//砸金蛋抽奖合
		for(var i=1;i<=2;i++){
			var objets = {};    //活动对象
			if(i==1){
				objets.itemId = $('#activity1').val();   //id
				objets.num = $scope.activity_num1;   // 次数
			}else if(i==2){
				objets.itemId = $('#activity2').val();   //id
				objets.num = $scope.activity_num2;   // 次数				
			}
			$scope.product.num.push(objets);  
		}
		//console.log($scope.product);
		$http({
			   url: path+"/server/updateOrder",
			   method: 'POST',
			   data:angular.toJson($scope.product)
		}).success(function(data){
			if(data.code == "0"){
				alert("操作成功！");
				$scope.product.consignee = "" ;   //收货人
				$scope.product.consigneePhone = "";  //联系电话
				$scope.product.consigneeAddress = "";  //送货地址
				$('.boxInfo2').val("");  //产品
				$scope.product.depositPrice = "";  //预付定金
				$scope.product.realPayPrice = "";  //本次实收金额
				$scope.product.isUseActivityCard = ""; //是否使用活动卡
				$scope.activity_name1 = "";     //砸金蛋
				$scope.activity_num1 = "";    	//砸金蛋个数
				$scope.activity_name2 = "";  	//礼品
				$scope.activity_num2 = "";		//礼品个数
				$scope.product.remarks = "";   //备注
				$scope.product.explain = "";    //说名
				$scope.booking_detail.center().close();   //关闭弹框  
				$scope.search();
			}
		}).error(function(data){
			console.log(data);   
		});
		
	}
	
	//提示信息
	$scope.alertMessage = function(message){
		alertModel.pannel = jqueryAlert({
			content: message,
			modal: true
		});
	}
	
	//全选，取消
	$scope.chooseAll = function(className,flag){
		publicService.chooseAllByClassName(className,flag);
	}
	
	//导出表格数据（1：筛选导出，2：选中导出）  
	$scope.downloadTableData = function(type){
		var paramObj = {};
		
		if(type==1){	//筛选导出
			paramObj = {
					page : 1, 
					pageSize : 10,
					ispage:false,
					param:{
						activityCode:$scope.search.order_code,//活动编号
						activityName:$scope.search.activity_names,//活动名称
						orderState:$('#orderState').val(),//订单状态
						filiale:$scope.search.filiale,//分公司
						shopName:$scope.search.shop_name,//专卖店名称
						sellerName:$scope.search.order_guide,//专属顾问
						productModel:$scope.search.product_type,   //产品型号
						customerPhone:$scope.search.phone,  //联系电话
						createTime:$('#order_down_time').val(),  //下单时间
						
						province:$('#province').val(),//省
						city:$('#city').val(), // 市
						district:$('#area').val(),//区
					}
			};
		}else if(type==2){	//选中导出
			var ids = publicService.getChooseValueByClassName("recordClass");
			if(ids.length==0){
				$scope.alertMessage("请选择订单！");
				return;
			}
			
			paramObj = {
					page : 1, 
					pageSize : 10,
					param:{
						ids: ids
					}
			};
		}

		var requestUrl = path+"/server/export";		//请求路径
		var exportModule = "order_module";			//模块名称
		var form = $("<form method='POST' action='"+requestUrl+"' target='_self'>"
						+"<input type='hidden' name='module_code' value='"+exportModule+"'/>"
						+"<input type='hidden' name='page' value='"+angular.toJson(paramObj)+"'/>"
					+"</form>");
		console.log("【表单参数】",form.serializeArray());
	    $(document.body).append(form);
	    form.submit();	
	}

	
	publicService.initProvince(1);			//初始化省
	publicService.initCity(1);				//初始化市
	publicService.initArea(1);				//初始化区
	publicService.initDate("order_down_time");   	 //订单时间
	$scope.orderStates();                         //订单状态
	$scope.orderTypes();       //订单类型
	$scope.getorderNum();      //活动列表的总金额和订单数量
//	publicService.initOrderState("orderState");     //订单状态
	
});